import MatterManager from '../../managers/MatterManager'

export default class BulletMatter extends Laya.Script{
    private matterManage =  MatterManager.instance;
    private container: Laya.Sprite;

    private bullet: any;
    private bulletX: number = 300;
    private bulletY: number = 1000;
    private bulletRadius: number = 25;
    private Veloctiy: number = 15;

    constructor() {
        super();
    }

    public onAwake(){
        this.container = this.owner as Laya.Sprite;
        this.container.pivot(this.container.width/2, this.container.height/2);

        this.bullet = this.matterManage.produceBall(this.bulletX, this.bulletY, this.bulletRadius); 
        this.bullet.collisionFilter = {
            category: 4, 
            mask: 1, 
            group: 0
        };
        this.bullet.label = 'bullet';
        this.bullet.parentContainer = this.container;

        this.matterManage.addToWorld(this.bullet);
        this.matterManage.setBallVec(this.bullet, 0, 0)
    }

    // 描边-->调试使用  子弹是运动的，换种描边方法
    // public drawBulletBorder(drawContainer: Laya.Sprite): void{
    //     this.matterManage.drawBodyBorder(drawContainer, this.bullet.vertices);
    // }

   public onUpdate(){
        // 必须牢记，前提是 container 和 bullet 的参考原点坐标相等
        this.container.x = this.bullet.position.x;
        this.container.y = this.bullet.position.y;

   }

   public setBulletVec(mouseX: number, mouseY: number): void{
        // 两个直角边，含正负
        let lengthX = mouseX - this.bulletX;
        let lengthY = mouseY - this.bulletY;
        let lengthZ = Math.sqrt(lengthX*lengthX + lengthY*lengthY);
        // 正弦求小球速度, 不能用余弦，只能用正弦
        let VeloctiyX = this.Veloctiy * (lengthX/lengthZ);
        let VeloctiyY = this.Veloctiy * (lengthY/lengthZ);

        //this.bullet.isStatic = false;
        this.matterManage.setBallVec(this.bullet, VeloctiyX, VeloctiyY);
   }

   public remveFromWord(){
       this.matterManage.remveFromWord(this.bullet);
   }

   public onDisable(){
       Laya.Pool.recover('bullet', this.owner);
   }
}